import axios from "@/request/index.js";

// get请求 -- json
export function get(url, params) {
	return new Promise((resolve, reject) => {
		axios
			.get(url, { params: params })
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}
// get请求格式为 /id/content; 注意返回数据
export function _get(url, params = []) {
	let p = ''
	params.forEach(item => {
		p += '/' + item
	})
	return new Promise((resolve, reject) => {
		axios
			.get(url + p)
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}
// post请求 -- json
export function post(url, params) {
	return new Promise((resolve, reject) => {
		axios
			.post(url, params)
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}

// delete请求 -- json
export function deleteData(url, params) {
	let param = {
		data: params
	}
	return new Promise((resolve, reject) => {
		axios
			.delete(url, param)
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}
// post请求 -- /id/content
// export function _post(url, params) {
//     return new Promise((resolve, reject) => {
//         axios.post(url, params).then(res => {
//             resolve(res.data);
//         }).catch(err => {
//             reject(err.data);
//         })
//     });
// }
// get请求 -- blob
export function getBlob(url, params = {}) {
	return new Promise((resolve, reject) => {
		axios
			.get(url, {
				params: params,
				responseType: 'blob'
			})
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}
// post请求 -- 表单
export function postForm(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios
			.post(url, data, {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			})
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}

function toFormData(o) {
	const formData = new FormData()
	for (let [key, value] of Object.entries(o)) {
		if (value !== undefined) {
			if (value == null) {
				value = ''
			}
			formData.append(key, value)
			continue
		}
	}
	return formData
}
// post请求 --formData格式
export function _postForm(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios
			.post(url, toFormData(data), {
				headers: {
					'content-type': 'multipart/form-data'
				}
			})
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}
